package com.atguigu.daijia.driver.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.driver.config.TencentCloudProperties;
import com.atguigu.daijia.driver.service.CiService;
import com.atguigu.daijia.driver.service.CosService;
import com.atguigu.daijia.model.vo.driver.CosUploadVo;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CosServiceImpl implements CosService {

    @Autowired
    private TencentCloudProperties tencentCloudProperties;

    private COSClient getPrivateCOSClient() {
        //初始化用户信息
        COSCredentials cred = new
                BasicCOSCredentials(tencentCloudProperties.getSecretId(),
                tencentCloudProperties.getSecretkey());
        ClientConfig clientConfig = new ClientConfig(new
                Region(tencentCloudProperties.getRegion()));
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }

    @Autowired
    private CiService ciService;

    @Override
    public CosUploadVo upload(MultipartFile file, String path) {
        //链接腾讯云
        COSClient cosClient = this.getPrivateCOSClient();
        //设置上传完数据信息
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(file.getSize());
        meta.setContentEncoding("UTF-8");
        meta.setContentType(file.getContentType());
        String fileType =
                file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")
                ); //文件后缀名
        String uploadPath = "/driver/" + path + "/" +
                UUID.randomUUID().toString().replaceAll("-", "") + fileType;
        //获取腾讯云的存储位置
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(tencentCloudProperties.getBucketPrivate(), uploadPath, file.getInputStream(), meta);
            putObjectRequest.setStorageClass(StorageClass.Standard);
            //上传
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            log.info(JSON.toJSONString(putObjectResult));
            cosClient.shutdown();
            //审核图片
            Boolean imageAuditing = ciService.imageAuditing(uploadPath);
            if (!imageAuditing){
                //删除图片
                cosClient.deleteObject(tencentCloudProperties.getBucketPrivate(), uploadPath);
                throw new GuiguException(ResultCodeEnum.IMAGE_AUDITION_FAIL);
            }

            CosUploadVo cosUploadVo = new CosUploadVo();
            cosUploadVo.setUrl(uploadPath);
            cosUploadVo.setShowUrl(this.getImageUrl(uploadPath));
            return cosUploadVo;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getImageUrl(String path) {
        if (!StringUtils.hasText(path)){
            return "";
        }
        COSClient cosClient = getPrivateCOSClient();
        //自动生成签名
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(tencentCloudProperties.getBucketPrivate(), path, HttpMethodName.GET);
        //生成的临时URL有效期为10分钟
        Date expirationDate = new DateTime().plusMinutes(10).toDate();
        request.setExpiration(expirationDate);
        URL url = cosClient.generatePresignedUrl(request);
        cosClient.shutdown();
        return url.toString();
    }
}